package com.linkgie.galaxyframework.crypto.context;

import com.linkgie.galaxyframework.crypto.Algorithm;
import com.linkgie.galaxyframework.crypto.CryptoDigester;
import com.linkgie.galaxyframework.crypto.spi.DigestGenerator;

/**
 * 摘要生成适配器；
 * 
 * @author liso
 *
 * @param <T> 对外呈现的类型；
 * @param <R> 内部被适配的类型；
 */
public abstract class AbstractDigesterAdaptor<T, R> implements CryptoDigester<R> {

	protected final Algorithm ALGORITHM;

	private DigestGenerator<T> digestGenerator;

	public AbstractDigesterAdaptor(Algorithm algorithm, DigestGenerator<T> digestGenerator) {
		this.ALGORITHM = algorithm;
		this.digestGenerator = digestGenerator;
	}

	@Override
	public Algorithm getAlgorithm() {
		return ALGORITHM;
	}

	@Override
	public AbstractDigesterAdaptor<T, R> update(byte[] data, int offset, int length) {
		digestGenerator.update(data, offset, length);
		return this;
	}

	@Override
	public R doFinal() {
		T digest = digestGenerator.doFinal();
		return apply(digest);
	}

	/**
	 * 转换摘要的类型；
	 * 
	 * @param digest 摘要数据；
	 * @return
	 */
	protected abstract R apply(T digest);

}
